package kr.co.redcircle.loader.data;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import kr.co.redcircle.loader.utility.ByteUtil;

public class MetaData extends ArrayList<String>{

	private static final long serialVersionUID = -7605103700305059409L;
	private byte[] metaByteArray;
	private int fieldCount = 0;
	private String dataName = null;
	private int nameEndPosition;
	private int recoridCount;
	
	public MetaData(byte[] metaBytes) {
		this.metaByteArray = metaBytes;
	}

	public void load() {
	
		try {
			
			this.recoridCount = getRecCount();
			this.dataName = getMetaSetName();
			this.fieldCount = getFCount();
			int i=0;
			int metaFieldIndex = this.nameEndPosition + 4;
			for (i=0; i<this.fieldCount; i++){
				String[] retString = getFieldName(metaFieldIndex);
				metaFieldIndex = Integer.parseInt(retString[0]);
				this.add(retString[1]);
//				System.out.println(retString[1] + ",");
			}
			
		} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
		}
	}
	
	public int getFieldCount() {
		return fieldCount;
	}

	public int getRecordCount() {
		return recoridCount;
	}

	private String[] getFieldName(int metaFieldIndex) throws UnsupportedEncodingException {

		int sizeIndex = metaFieldIndex += 8;
		byte[] metaNameCountArray = new byte[2];
		System.arraycopy(this.metaByteArray, sizeIndex, metaNameCountArray, 0, 2);
		int size = ByteUtil.byteArrayToInt(metaNameCountArray);
		sizeIndex += 2;
		byte[] metaNameStringArray = new byte[size];
		System.arraycopy(this.metaByteArray, sizeIndex, metaNameStringArray, 0, size);
		
		String[] retString = new String[2];
		retString[0] = (sizeIndex + size + 1) + "";
		retString[1] = new String(metaNameStringArray, "utf-8");

		return retString;
	}

	private int getRecCount() {
		byte[] cntByte = new byte[4];
		System.arraycopy(this.metaByteArray, this.metaByteArray.length - 4, cntByte, 0, 4);
		return ByteUtil.byteArrayToInt(cntByte);
	}

	private int getFCount() {
		byte[] cntByte = new byte[4];
		System.arraycopy(this.metaByteArray, this.nameEndPosition, cntByte, 0, 4);
		return ByteUtil.byteArrayToInt(cntByte);
	}

	private String getMetaSetName() throws UnsupportedEncodingException {
		byte[] nameByte = new byte[4];
		System.arraycopy(this.metaByteArray, 0, nameByte, 0, 4);
		int nameLength = ByteUtil.byteArrayToInt(nameByte);
		byte[] nameValueByte = new byte[nameLength];
		System.arraycopy(this.metaByteArray, 4, nameValueByte, 0, nameLength);
		this.nameEndPosition = 4 + nameLength + 16;
		return new String(nameValueByte, "utf-8");
	}

}
